package com.mengdie.shuidi.ui.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebBackForwardList;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.utils.LogUtils;
import com.mengdie.shuidi.R;
import com.mengdie.shuidi.event.MesEvent;
import com.mengdie.shuidi.manager.MDAccountMgr;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 作者：HQY on 16/10/29 15:34
 * 邮箱：hqy_xz@126.com
 */

public class WebViewActivity extends BaseActivity {

    public ValueCallback<Uri> mUploadMessage;
    public ValueCallback<Uri[]> mUploadMessageForAndroid5;

    public final static int FILECHOOSER_RESULTCODE = 1;
    public final static int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 2;
    ProgressDialog progressBar;
    @Bind(R.id.rl_title_all)
    RelativeLayout mRlTitleAll;

    @Bind(R.id.rl_generic_back)
    RelativeLayout mRlGenericBack;
    @Bind(R.id.tv_generic_title)
    TextView mTvGenericTitle;
    @Bind(R.id.wv_generic)
    WebView mWebView;

    private String title;

    private String mCurUrl;

    private int num = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        ButterKnife.bind(this);
        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {
            title = bundle.getString("title");

            if (title.equals("售后服务")) {
                mRlTitleAll.setVisibility(View.GONE);
                mCurUrl = bundle.getString("url");
            } else {
                mCurUrl = bundle.getString("url") + "?session_id=" + MDAccountMgr.getInstance().getSessionId() + "&origin=android";
                mRlTitleAll.setVisibility(View.VISIBLE);
            }
        }
        init();

    }

    public void init() {
        mTvGenericTitle.setText(title);
        progressBar = new ProgressDialog(this);
        progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);

        LogUtils.e("URL:" + mCurUrl);
        mRlGenericBack.setVisibility(View.VISIBLE);
        mRlGenericBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mWebView != null && mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    finish();
                }
            }
        });

        initWebView();
        clearCoolies(WebViewActivity.this);
        Logger.e(mCurUrl);
        mWebView.loadUrl(mCurUrl);


    }

    @JavascriptInterface
    private void initWebView() {
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true); // 启用支持javascript
        webSettings.setAllowFileAccess(true); // 可以访问文件
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setAppCacheEnabled(false);
        webSettings.setDomStorageEnabled(true); // 开启 DOM storage API 功能
        String ua = webSettings.getUserAgentString();
        webSettings.setUserAgentString(ua + "(MDAPP)");
        // 先加载网页再加载图片
        if (Build.VERSION.SDK_INT >= 19) {
            mWebView.getSettings().setLoadsImagesAutomatically(true);
        } else {
            mWebView.getSettings().setLoadsImagesAutomatically(false);
        }
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.clearHistory();
        mWebView.clearFormData();
        mWebView.clearCache(true);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //handler.sendEmptyMessage(0);
                view.loadUrl(url);
                LogUtils.e("URL:" + url);
                if (url.contains("pay")) {
                    num++;
                    if (num == 1) {
                        EventBus.getDefault().post(new MesEvent(1));
                    }
                    finish();
                } else if (url.equals("http://www.baidu.com/")) {
                    finish();
                }
                return true;
            }

        });
        mWebView.setWebChromeClient(new WebChromeClient() {
                                        public void onProgressChanged(WebView view, int progress) {// 载入进度改变而触发
                                            if (progress == 100) {
                                                //handler.sendEmptyMessage(1);// 如果全部载入,隐藏进度对话框
                                            }
                                            super.onProgressChanged(view, progress);
                                        }

                                        //扩展支持alert事件
                                        @Override
                                        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                                            AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                                            builder.setTitle("xxx提示").setMessage(message).setPositiveButton("确定", null);
                                            builder.setCancelable(false);
                                            builder.setIcon(R.drawable.ic_launcher);
                                            AlertDialog dialog = builder.create();
                                            dialog.show();
                                            result.confirm();
                                            return true;
                                        }

                                        //扩展浏览器上传文件
                                        //3.0++版本
                                        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                                            openFileChooserImpl(uploadMsg);
                                        }

                                        //3.0--版本
                                        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                                            openFileChooserImpl(uploadMsg);
                                        }

                                        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                                            openFileChooserImpl(uploadMsg);
                                        }

                                        // For Android > 5.0
                                        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> uploadMsg, WebChromeClient.FileChooserParams fileChooserParams) {
                                            openFileChooserImplForAndroid5(uploadMsg);
                                            return true;
                                        }
                                    }
        );

//        mWebView.addJavascriptInterface(new BrowserInterface(this), "BrowserInterface");
    }

    private void openFileChooserImpl(ValueCallback<Uri> uploadMsg) {
        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
    }

    private void openFileChooserImplForAndroid5(ValueCallback<Uri[]> uploadMsg) {
        mUploadMessageForAndroid5 = uploadMsg;
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.setType("image/*");

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");

        startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE_FOR_ANDROID_5);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mWebView.canGoBack() && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            //获取历史列表
            WebBackForwardList mWebBackForwardList = mWebView
                    .copyBackForwardList();
            //判断当前历史列表是否最顶端,其实canGoBack已经判断过
            if (mWebBackForwardList.getCurrentIndex() > 0) {
                mWebView.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage)
                return;
            Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;

        } else if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {
            if (null == mUploadMessageForAndroid5)
                return;
            Uri result = (intent == null || resultCode != RESULT_OK) ? null : intent.getData();
            if (result != null) {
                mUploadMessageForAndroid5.onReceiveValue(new Uri[]{result});
            } else {
                mUploadMessageForAndroid5.onReceiveValue(new Uri[]{});
            }
            mUploadMessageForAndroid5 = null;
        }
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {// 定义一个Handler，用于处理下载线程与UI间通讯
            if (!Thread.currentThread().isInterrupted()) {
                switch (msg.what) {
                    case 0:
                        progressBar.show();// 显示进度对话框
                        break;
                    case 1:
                        progressBar.hide();// 隐藏进度对话框，不可使用dismiss()、cancel(),否则再次调用show()时，显示的对话框小圆圈不会动。
                        break;
                }
            }

            super.handleMessage(msg);
        }
    };

    private void clearCoolies(Context context) {
        @SuppressWarnings("unused")
        CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookie();
        cookieManager.removeAllCookie();
    }


    @OnClick(R.id.rl_generic_back)
    public void onClick() {
        onBackPressed();
    }
}
